<?php

namespace common\models\trade;

use Yii;
use yii\base\Exception;
use Alipay\aop\request\alipay\TradeRequest;
use common\helpers\IpHelper;
use common\helpers\Url;

/**
 * This is the model class for table "{{%trade}}".
 */
class UnifiedPayment extends Trade {

    /**
     * 获取调起支付时支付宝所需的参数
     */
    public function getAlipay() {
        if ($this->paymode !== static::PAYMODE_ALIPAY) {
            return '';
        }
        if (!$this->partner) {
            return '';
        }
        if (Yii::$app->id == 'app-apiend') {
            $requestName = TradeRequest::REQUEST_APP_PAY;
            $request = new TradeRequest($requestName);
            $bizContent = [
                'out_trade_no' => $this->trade_no,
                'total_amount' => $this->cash,
                'subject' => $this->subject,
                'body' => $this->body,
                'timeout_express' => '15m',
                'notify_url' => $this->getNotifyUrl(),
                'time_expire' => date('Y-m-d H:i', $this->expire_time),
            ];
            $request->setBizContent($bizContent);
            $alipay = Yii::$app->alipay->transport($this->partner->account_id);
            $response = $alipay->sdkExecute($request);
            return $response;
        }
        if (Yii::$app->id == 'app-mpend') {
            $requestName = TradeRequest::REQUEST_WAP_PAY;
            $request = new TradeRequest($requestName);
            $request->setNotifyUrl($this->getNotifyUrl());
            $request->setReturnUrl($this->getReturnUrl());
            $bizContent = [
                'body' => $this->body,
                'subject' => $this->subject,
                'out_trade_no' => $this->trade_no,
                'timeout_express' => '30m',
                'time_expire' => date('Y-m-d H:i', $this->expire_time),
                'total_amount' => $this->cash,
                'quit_url' => $this->getReturnUrl(),
                'product_code' => 'QUICK_WAP_WAY',
            ];
            $request->setBizContent($bizContent);
            $alipay = Yii::$app->alipay->transport($this->partner->account_id);
//            $response = $alipay->sdkExecute($request);
            $response = $alipay->pageExecute($request);
            return $response;
        }
    }

    /**
     * 获取调起支付时微信所需的参数
     */
    public function getWechat() {
        if ($this->paymode !== static::PAYMODE_WECHAT) {
            return null;
        }
        if (function_exists('bcmul')) {
            $total = bcmul($this->cash, 100);
        } else {
            $total = (int) (($this->cash * 1000) / 10);
        }
        if ($total <= 0) {
            return null;
        }
        $attributes = [
            'trade_type' => $this->getTradeType(),
            'body' => Yii::$app->name . '-' . $this->subject,
            'detail' => $this->body,
            'out_trade_no' => $this->trade_no,
            'total_fee' => $total,
            'spbill_create_ip' => IpHelper::ip(false),
            'notify_url' => $this->getNotifyUrl(),
            'time_expire' => date('YmdHis', $this->expire_time),
        ];
        $wechatPay = null;
        if ($this->tradeType == 'APP') {
            $wechatPay = Yii::$app->wxpay;
        } elseif ($this->tradeType == 'JSAPI') {
            $openid = $this->getOpenid();
            if ($openid == null) {
                Yii::error('需要openid');
                return null;
            }
            $attributes['openid'] = $openid;
            static::log(['Trade attributes', $attributes]);
            $wechatPay = Yii::$app->mppay;
            $payment = $wechatPay->payment([
                'class' => '\common\components\wechat\models\UnifiedOrder'
            ]);
            $payment->attributes = $attributes;
            static::log(['wxpay API UnifiedOrder attributes', $payment->attributes]);
            $data = $payment->save();
            if (!$data) {
                $data = $payment->getErrors();
                static::log(['JSAPI ERROR', $data]);
            } else {
                static::log(['UnifiedOrder Data', $data]);
                $jsApiParameters = $wechatPay->getJsApiParameters($data);
            }
            static::log(['Trade Before-attributes', $this->attributes]);
            static::log(['JsApiParameters', $jsApiParameters]);
            return $jsApiParameters;
        } elseif ($this->tradeType == 'MWEB') {
            $attributes['scene_info'] = \yii\helpers\Json::encode([
                'h5_info' => [
                    'type' => '',
                    'wap_url' => $this->getReturnUrl(),
                    'wap_name' => '优越定制',
                ]
            ]);
            static::log(['Trade attributes', $attributes]);
            $wechatPay = Yii::$app->mppay;
            $payment = $wechatPay->payment([
                'class' => '\common\components\wechat\models\UnifiedOrder'
            ]);
            $payment->attributes = $attributes;
            static::log(['wxpay API UnifiedOrder attributes', $payment->attributes]);
            $data = $payment->save();
            if (!$data) {
                $data = $payment->getErrors();
                static::log(['JSAPI ERROR', $data]);
            } else {
                static::log(['UnifiedOrder Data', $data]);
                try {
                    $jsApiParameters = $wechatPay->getJsApiParameters($data);
                } catch (Exception $exc) {
                    return $this->dumpError($exc->getMessage());
                }
            }
            static::log(['Trade Before-attributes', $this->attributes]);
            static::log(['JsApiParameters', $jsApiParameters]);
            return $jsApiParameters;
        } else {
            return null;
        }

        return $wechatPay->prepay($attributes);
    }

    public function getNotifyUrl() {
        return Url::callbackPayment($this->paymode);
    }

    public function getReturnUrl() {
        if ($this->return_url) {
            return $this->return_url;
        }
        return Url::wap('/order');
    }

    public function setReturnUrl($scope, $id) {
        $uri = [];
        if ($scope == 'shop') {
            $uri = ['/order/view/' . $id];
        }
        if (!empty($uri)) {
            $this->return_url = Url::wap($uri);
        }
    }

    public function getOpenid() {
        $data = $this->getConnectUser(\common\models\user\UserConnect::CLIENT_WECHAT)->one();
        if ($data) {
            return $data->openid;
        }
        return null;
    }

    public function fields() {
        return [
            'id',
            'paymode' => function() {
                return (string) $this->paymode;
            },
            'wechat',
            'alipay',
        ];
    }

}
